import NProgress from 'nprogress'
import request from './request'

const showError = (msg) => {
  console.error('message', msg)
  this.$notify({
    message: '系统异常,请联系管理员'
  });
}

const _get = (url, params) => {
  NProgress.start()
  NProgress.inc()
  return new Promise((resolve, reject) => {
    request({
      method: 'get',
      url: url,
      params: params
    }).then(res => {
      // eslint-disable-next-line eqeqeq
      if (res && res.success === false && res.message) {
        showError(res.message)
        reject(res.message)
      } else {
        resolve(res)
      }
      NProgress.done()
    }).catch((msg) => {
      NProgress.done()
    })
  })
}

const _post = (url, params, data) => {
  NProgress.start()
  NProgress.inc()
  return new Promise((resolve, reject) => {
    request({
      method: 'post',
      url: url,
      data: data,
      params: params
    }).then(res => {
      if (res && res.success === false && res.code === 99999) {
        showError(res.message || '')
        reject(res.message || '')
      } else {
        resolve(res)
      }
      NProgress.done()
    }).catch((msg) => {
      NProgress.done()
      reject(msg)
    })
  })
}

const _postxf = (url, data) => {
  NProgress.start()
  NProgress.inc()
  const config = {
    method: 'post',
    url: url,
    data: data,
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'
    }
  }
  return new Promise((resolve, reject) => {
    request(config).then(res => {
      // eslint-disable-next-line eqeqeq
      if (res && res.success === false && res.message) {
        this.$notify({
          message: res.message,
          offset: 100
        });
      } else {
        resolve(res)
      }
      NProgress.done()
    }).catch((msg) => {
      NProgress.done()
    })
  })
}

export default {
  get: _get,
  post: _post,
  postxf: _postxf
}
